package com.fzhucc.modules.lesson.service.impl;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.Msg.domain.Msg;
import com.fzhucc.modules.Msg.domain.dto.SmallMsgDto;
import com.fzhucc.modules.Msg.repository.MsgRepository;
import com.fzhucc.modules.activity.domain.Activity;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.lesson.domain.*;
import com.fzhucc.modules.lesson.domain.dto.*;
import com.fzhucc.modules.lesson.repository.*;
import com.fzhucc.modules.lesson.service.LessonService;
import com.fzhucc.modules.lesson.service.mapstruct.LessonMapper;
import com.fzhucc.modules.lesson.service.mapstruct.LessonRecordMapper;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.domain.UserSmall;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.repository.UserSmallRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.modules.system.service.dto.UserDto;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author yyg
 * @description 服务实现
 * @date 2022-12-07
 **/
@Service
@RequiredArgsConstructor
public class LessonServiceImpl implements LessonService {

    private final LessonRepository lessonRepository;
    private final LessonMapper lessonMapper;

    private final UserRepository userRepository;

    private final MsgRepository msgRepository;

    private final UserSmallRepository userSmallRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${fen.type.xt}")
    public String xt;

    private final LessonRecordMapper lessonRecordMapper;
    private final LessonIntegralRepository lessonIntegralRepository;

    private final LessonRecordRepository lessonRecordRepository;

    private final UserService userService;

    private final LessonLabelRepository lessonLabelRepository;

    private final LessonFirstChapterRepository lessonFirstChapterRepository;

    private final LessonSecondChapterRepository lessonSecondChapterRepository;

    private final LessonLearnRecordRepository lessonLearnRecordRepository;

    private final DictService dictService;

    private final FenRecordLogService fenRecordLogService;

    private final DictDetailService dictDetailService;

    @Override
    public Map<String, Object> queryAll(LessonQueryCriteria criteria, Pageable pageable) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(xt);
        } catch (Exception e) {

        }
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        criteria.setIsDelete(0);
        Page<Lesson> page = lessonRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<LessonDto> res = page.map(lessonMapper::toDto);
        List<LessonDto> list = res.getContent();
        for (int i = 0; i < list.size(); i++) {
            LessonDto lessonDto = list.get(i);
            List<LessonLabel> list_lessonLabels = lessonLabelRepository.findByLessonId(lessonDto.getId());
            if (list_lessonLabels != null && list_lessonLabels.size() > 0) {
                List<String> listlabel = new ArrayList<String>();
                for (LessonLabel lessonLabel : list_lessonLabels) {
                    listlabel.add(lessonLabel.getLabelName());
                }
                lessonDto.setLabels(listlabel);
            }

            List<LessonFirstChapter> list1 = lessonFirstChapterRepository.findByLessonId(lessonDto.getId());
            List<LessonFirstChapterDto> lessonFirstChapterDtolist = new ArrayList<LessonFirstChapterDto>();
            for (LessonFirstChapter lessonFirstChapter : list1) {
                LessonFirstChapterDto lessonFirstChapterDto = new LessonFirstChapterDto();
                lessonFirstChapterDto.setId(lessonFirstChapter.getId());
                lessonFirstChapterDto.setName(lessonFirstChapter.getName());
                lessonFirstChapterDto.setType(lessonFirstChapter.getType());
                lessonFirstChapterDto.setUrl(lessonFirstChapter.getUrl());
                lessonFirstChapterDto.setLessonSecondChapterList(lessonSecondChapterRepository.findByFirstChapterId(lessonFirstChapter.getId()));
                lessonFirstChapterDtolist.add(lessonFirstChapterDto);
            }
            lessonDto.setLessonFirstChapterList(lessonFirstChapterDtolist);
        }
        //TODO 传进来的id等于返回的id  且list size为1则 判断为byId查询热度+1
        List<LessonDto> listLes = res.getContent();
        if (listLes != null) {
            if (listLes.size() == 1) {
                LessonDto lessonDto = listLes.get(0);
                if (lessonDto.getId() == criteria.getId()) {
                    //查询热度 +1
                    Optional<Lesson> reslesson = lessonRepository.findById(lessonDto.getId());
                    if (reslesson.isPresent()) {
                        Integer hot = reslesson.get().getHot();
                        reslesson.get().setHot(hot + 1);
                        Lesson save = lessonRepository.save(reslesson.get());
                        for (LessonDto dto : listLes) {
                            dto.setHot(save.getHot());
                        }
                    }
                    //TODO 如果是登录用户则记录一次 学习完成的情况
                    Long userId = null;
                    try {
                        userId = SecurityUtils.getCurrentUserId();
                    } catch (Exception e) {

                    }
                    if (userId != null) {
                        //先删除原来的记录在保存新的学习记录
                        List<LessonLearnRecord> lists = lessonLearnRecordRepository.findByUserIdAndLessonIdLists(userId, lessonDto.getId());
                        if (lists != null && lists.size() > 0) {
                            for (LessonLearnRecord lessonLearnRecord : lists) {
                                lessonLearnRecordRepository.deleteById(lessonLearnRecord.getId());
                            }
                        }
                        LessonLearnRecord lessonLearnRecord = new LessonLearnRecord();
                        lessonLearnRecord.setLabel("已学习");
                        lessonLearnRecord.setLearnFinishTime(new Timestamp(new Date().getTime()));
                        lessonLearnRecord.setUserId(userId);
                        lessonLearnRecord.setLessonId(lessonDto.getId());
                        lessonLearnRecordRepository.save(lessonLearnRecord);
                    }

                }
            }
        }

        List<LessonDto> list2 = res.getContent();
        if (list2!=null && list2.size()>0){
            for (LessonDto lessonDto:list2){
                List<Msg> listMsg = msgRepository.findNormalByGlIdWithAuditStatus(lessonDto.getId(), "审核通过","%学堂%");
                if (listMsg != null && listMsg.size() > 0) {
                    List<SmallMsgDto> myList = new ArrayList<SmallMsgDto>();
                    for (Msg msg : listMsg) {
                        SmallMsgDto smallMsgDto = new SmallMsgDto();
                        smallMsgDto.setId(msg.getId());
                        smallMsgDto.setGlId(msg.getGlId());
                        smallMsgDto.setType(msg.getType());
                        smallMsgDto.setContext(msg.getContext());
                        smallMsgDto.setAuditStatus(msg.getAuditStatus());
                        smallMsgDto.setUserId(msg.getUserId());
                        smallMsgDto.setUpdateBy(msg.getUpdateBy());
                        smallMsgDto.setCreateTime(msg.getCreateTime());
                        smallMsgDto.setCreateBy(msg.getCreateBy());
                        smallMsgDto.setUpdateTime(msg.getUpdateTime());
                        Optional<UserSmall> res2 = userSmallRepository.findById(msg.getUserId());
                        if (res2.isPresent()) {
                            smallMsgDto.setUserSmall(res2.get());
                        }
                        myList.add(smallMsgDto);
                    }
                    lessonDto.setMsgDto(myList);
                }
            }
        }
        return PageUtil.toPage(res);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(LessonQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }

    @Override
    public List<LessonDto> queryAll(LessonQueryCriteria criteria) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        criteria.setIsDelete(0);
        return lessonMapper.toDto(lessonRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public LessonDto findById(Integer id) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(xt);
        } catch (Exception e) {

        }

        Lesson lesson = lessonRepository.findById(id).orElseGet(Lesson::new);
        ValidationUtil.isNull(lesson.getId(), "Lesson", "id", id);
        LessonDto lessonDto = lessonMapper.toDto(lesson);

        List<Msg> listMsg = msgRepository.findNormalByGlIdWithAuditStatus(lessonDto.getId(), "审核通过","%学堂%");
        if (listMsg != null && listMsg.size() > 0) {
            List<SmallMsgDto> myList = new ArrayList<SmallMsgDto>();
            for (Msg msg : listMsg) {
                SmallMsgDto smallMsgDto = new SmallMsgDto();
                smallMsgDto.setId(msg.getId());
                smallMsgDto.setGlId(msg.getGlId());
                smallMsgDto.setType(msg.getType());
                smallMsgDto.setContext(msg.getContext());
                smallMsgDto.setAuditStatus(msg.getAuditStatus());
                smallMsgDto.setUserId(msg.getUserId());
                smallMsgDto.setUpdateBy(msg.getUpdateBy());
                smallMsgDto.setCreateTime(msg.getCreateTime());
                smallMsgDto.setCreateBy(msg.getCreateBy());
                smallMsgDto.setUpdateTime(msg.getUpdateTime());
                Optional<UserSmall> res = userSmallRepository.findById(msg.getUserId());
                if (res.isPresent()) {
                    smallMsgDto.setUserSmall(res.get());
                }
                myList.add(smallMsgDto);
            }
            lessonDto.setMsgDto(myList);
        }
        return lessonDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LessonDto create(Lesson resources) {
        resources.setOrgArea(orgAreaReturn());
        resources.setHot(0);
        return lessonMapper.toDto(lessonRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LessonDto createLessonWithChapter(LessonWithChapterDto resources) {
        Lesson lesson = new Lesson();
        LessonDto lessonDto = new LessonDto();
        List<String> listlastlabes = new ArrayList<String>();
        List<LessonFirstChapterDto> last_LessonFirstChapterDto = new ArrayList<LessonFirstChapterDto>();
        List<LessonSecondChapter> last_LessonSecondChapter = new ArrayList<LessonSecondChapter>();

        lesson.setName(resources.getName());
        lesson.setCoverUrl(resources.getCoverUrl());
        lesson.setCoursePoints(resources.getCoursePoints());
        lesson.setStarttime(resources.getStarttime());
        lesson.setEndtime(resources.getEndtime());
        lesson.setIsUnlimitedTime(resources.getIsUnlimitedTime());
        lesson.setIsShow(resources.getIsShow());
        lesson.setSort(resources.getSort());
        lesson.setIsPush(resources.getIsPush());
        lesson.setIsDelete(0);
        lesson.setHot(0);
        lesson.setOrgArea(orgAreaReturn());
        lesson.setType(resources.getType());
        lesson.setIntroduce(resources.getIntroduce());
        //创建课程主体
        Lesson newLesson = lessonRepository.save(lesson);
        if (resources.getLessonFirstChapterList() != null && resources.getLessonFirstChapterList().size() > 0) {
            List<LessonFirstChapterDto> list = resources.getLessonFirstChapterList();
            for (LessonFirstChapterDto lessonFirstChapterDto : list) {
                //创建一级分类
                LessonFirstChapter lessonFirstChapter = new LessonFirstChapter();
                lessonFirstChapter.setName(lessonFirstChapterDto.getName());
                lessonFirstChapter.setType(lessonFirstChapterDto.getType());
                lessonFirstChapter.setUrl(lessonFirstChapterDto.getUrl());
                lessonFirstChapter.setLessonId(newLesson.getId());
                LessonFirstChapter lessonFirstChapter1 = lessonFirstChapterRepository.save(lessonFirstChapter);

                //创建二级分类
                List<LessonSecondChapter> list2 = lessonFirstChapterDto.getLessonSecondChapterList();
                if (list2 != null && list2.size() > 0) {
                    for (LessonSecondChapter lessonSecondChapter : list2) {
                        lessonSecondChapter.setFirstChapterId(lessonFirstChapter1.getId());
                        LessonSecondChapter lessonSecondChapter1 = lessonSecondChapterRepository.save(lessonSecondChapter);
                        last_LessonSecondChapter.add(lessonSecondChapter1);
                    }
                }
                LessonFirstChapterDto lsatlessonFirstChapterDto = new LessonFirstChapterDto();
                lsatlessonFirstChapterDto.setId(lessonFirstChapter1.getId());
                lsatlessonFirstChapterDto.setName(lessonFirstChapter1.getName());
                lsatlessonFirstChapterDto.setType(lessonFirstChapter1.getType());
                lsatlessonFirstChapterDto.setUrl(lessonFirstChapter1.getUrl());
                lsatlessonFirstChapterDto.setLessonSecondChapterList(last_LessonSecondChapter);
                last_LessonFirstChapterDto.add(lsatlessonFirstChapterDto);
            }
        }

        //先删除课程原有标签  在绑定新的标签
        lessonLabelRepository.deleteByLessonId(newLesson.getId());
        if (resources.getLabels() != null) {
            for (String label : resources.getLabels()) {
                LessonLabel lessonLabel = new LessonLabel();
                lessonLabel.setLessonId(newLesson.getId());
                lessonLabel.setLabelName(label);
                LessonLabel lessonLabel_res = lessonLabelRepository.save(lessonLabel);
                if (lessonLabel_res != null) {
                    listlastlabes.add(lessonLabel_res.getLabelName());
                }
            }
        }

        lessonDto.setId(newLesson.getId());
        lessonDto.setName(newLesson.getName());
        lessonDto.setCoverUrl(newLesson.getCoverUrl());
        lessonDto.setCoursePoints(newLesson.getCoursePoints());
        lessonDto.setStarttime(newLesson.getStarttime());
        lessonDto.setEndtime(newLesson.getEndtime());
        lessonDto.setIsUnlimitedTime(newLesson.getIsUnlimitedTime());
        lessonDto.setIsShow(newLesson.getIsShow());
        lessonDto.setIsPush(newLesson.getIsPush());
        lessonDto.setType(newLesson.getType());
        lessonDto.setSort(newLesson.getSort());
        lessonDto.setHot(newLesson.getHot());
        lessonDto.setIntroduce(newLesson.getIntroduce());
        lessonDto.setLabels(listlastlabes);
        lessonDto.setOrgArea(newLesson.getOrgArea());
        lessonDto.setLessonFirstChapterList(last_LessonFirstChapterDto);
        return lessonDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editLessonWithChapter(LessonWithChapterDto lessonWithChapterDto) {
        Lesson lesson = lessonRepository.findById(lessonWithChapterDto.getId()).orElseGet(Lesson::new);
        ValidationUtil.isNull(lesson.getId(), "Lesson", "id", lessonWithChapterDto.getId());
        //先删除二级分类
        List<LessonFirstChapter> listLessonFirstChapter = lessonFirstChapterRepository.findByLessonId(lessonWithChapterDto.getId());
        if (listLessonFirstChapter != null && listLessonFirstChapter.size() > 0) {
            for (LessonFirstChapter lessonFirstChapter : listLessonFirstChapter) {
                lessonSecondChapterRepository.deleteByFirstChapterId(lessonFirstChapter.getId());
            }
        }
        //在删除一级分类
        lessonFirstChapterRepository.deleteByLessonId(lessonWithChapterDto.getId());
        lesson.setId(lessonWithChapterDto.getId());
        lesson.setName(lessonWithChapterDto.getName());
        lesson.setCoverUrl(lessonWithChapterDto.getCoverUrl());
        lesson.setCoursePoints(lessonWithChapterDto.getCoursePoints());
        lesson.setStarttime(lessonWithChapterDto.getStarttime());
        lesson.setEndtime(lessonWithChapterDto.getEndtime());
        lesson.setIsUnlimitedTime(lessonWithChapterDto.getIsUnlimitedTime());
        lesson.setIsShow(lessonWithChapterDto.getIsShow());
        lesson.setOrgArea(orgAreaReturn());
        lesson.setSort(lessonWithChapterDto.getSort());
        lesson.setIsPush(lessonWithChapterDto.getIsPush());
        lesson.setType(lessonWithChapterDto.getType());
        lesson.setIntroduce(lessonWithChapterDto.getIntroduce());
        Lesson newLesson = lessonRepository.save(lesson);
        List<LessonFirstChapterDto> listChapter = lessonWithChapterDto.getLessonFirstChapterList();
        if (listChapter != null && listChapter.size() > 0) {
            for (LessonFirstChapterDto lessonFirstChapterDto : listChapter) {
                //创建一级分类
                LessonFirstChapter lessonFirstChapter = new LessonFirstChapter();
                lessonFirstChapter.setName(lessonFirstChapterDto.getName());
                lessonFirstChapter.setType(lessonFirstChapterDto.getType());
                lessonFirstChapter.setUrl(lessonFirstChapterDto.getUrl());
                lessonFirstChapter.setLessonId(newLesson.getId());
                LessonFirstChapter lessonFirstChapter1 = lessonFirstChapterRepository.save(lessonFirstChapter);
                //创建二级分类
                List<LessonSecondChapter> list2 = lessonFirstChapterDto.getLessonSecondChapterList();
                if (list2 != null && list2.size() > 0) {
                    for (LessonSecondChapter lessonSecondChapter : list2) {
                        lessonSecondChapter.setFirstChapterId(lessonFirstChapter1.getId());
                        lessonSecondChapterRepository.save(lessonSecondChapter);
                    }
                }
            }
        }
        //先删除课程原有标签  在绑定新的标签
        lessonLabelRepository.deleteByLessonId(newLesson.getId());
        if (lessonWithChapterDto.getLabels() != null) {
            for (String label : lessonWithChapterDto.getLabels()) {
                LessonLabel lessonLabel = new LessonLabel();
                lessonLabel.setLessonId(newLesson.getId());
                lessonLabel.setLabelName(label);
                lessonLabelRepository.save(lessonLabel);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Lesson resources) {
        Lesson lesson = lessonRepository.findById(resources.getId()).orElseGet(Lesson::new);
        ValidationUtil.isNull(lesson.getId(), "Lesson", "id", resources.getId());
        lesson.copy(resources);
        lesson.setOrgArea(orgAreaReturn());
        lessonRepository.save(lesson);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //lessonRepository.deleteById(id);
            //修改为假删除
            Optional<Lesson> res = lessonRepository.findById(id);
            if (res.isPresent()) {
                Lesson lesson = res.get();
                lesson.setIsDelete(1);
                lessonRepository.save(lesson);
            }
        }
    }

    @Override
    public void download(List<LessonDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LessonDto lesson : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("课程名称", lesson.getName());
            map.put("课程封面", lesson.getCoverUrl());
            map.put("课程积分(学习此课程所需积分)", lesson.getCoursePoints());
            map.put("课程上线开始时间", lesson.getStarttime());
            map.put("课程上线结束时间", lesson.getEndtime());
            map.put("是否不限制上线开始结束时间 默认限制     0不限制(永久)   1限制", lesson.getIsUnlimitedTime());
            map.put("是否展示", lesson.getIsShow());
            map.put("是否推送首页", lesson.getIsPush());
            map.put("课程分类", lesson.getType());
            map.put("课程介绍", lesson.getIntroduce());
            map.put("区域划分", lesson.getOrgArea());
            map.put("排序", lesson.getSort());
            map.put("热度", lesson.getHot());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional
    public LessonRecord buyLesson(Integer lesson_id) {
        LessonRecord lessonRecord = new LessonRecord();
        boolean buyFlag = false;
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        Optional<Lesson> res = lessonRepository.findById(lesson_id);
        if (!res.isPresent()) {
            throw new BadRequestException("课程未找到");
        }
        Lesson lesson = res.get();
        if (lesson.getIsUnlimitedTime() == 0) {
            buyFlag = true;
        }
        if (lesson.getIsUnlimitedTime() == 1) {
            Timestamp starttime = lesson.getStarttime();
            Timestamp endtime = lesson.getEndtime();
            Date date = new Date();
            Timestamp nowtime = new Timestamp(date.getTime());
            if (starttime == null) {
                throw new BadRequestException("课程上线时间为null");
            }
            if (endtime == null) {
                throw new BadRequestException("课程下线时间为null");
            }
            if (starttime.getTime() <= nowtime.getTime() && endtime.getTime() >= nowtime.getTime()) {
                buyFlag = true;
            } else {
                throw new BadRequestException("该课程不在上线时间内");
            }
        }
        if (buyFlag) {
//            LessonIntegral lessonIntegral = lessonIntegralRepository.findByUserId(userId);
            UserDto userDto = userService.findById(userId);
            if (userDto.getIntegral() == null) {
                throw new BadRequestException("未找到用户积分");
            }
            List<LessonRecord> list_lessonRecord = lessonRecordRepository.findByUserIdAndLessonId(userId, lesson.getId());
            if (list_lessonRecord != null && list_lessonRecord.size() > 0) {
                throw new BadRequestException("您以购买过此课程，请勿重复购买");
            }
            Integer integral = userDto.getIntegral();//用户拥有的积分
            if (integral < 50) {
                throw new BadRequestException("积分不足");
            }
            int result_integral = integral - 50;
            userDto.setIntegral(result_integral);

            userService.updateIntegral(userId, result_integral);
            lessonRecord.setUserId(userId);
            lessonRecord.setLessonId(lesson.getId());
            lessonRecord.setOrgArea(orgAreaReturn());//设置区域划分
            lessonRecord.setBuyTime(new Timestamp(new Date().getTime()));
            lessonRecordRepository.save(lessonRecord);
        }
        return lessonRecord;
    }

    @Override
    public List<LessonRecordDto> getLessonRecord() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        List<LessonRecordDto> list_result = new ArrayList<LessonRecordDto>();
        List<LessonRecord> list = lessonRecordRepository.findByUserId(userId);
        for (LessonRecord lessonRecord : list) {
            LessonRecordDto lessonRecordDto = new LessonRecordDto();
            lessonRecordDto.setUserDto(userService.findById(lessonRecord.getUserId()));
            Optional<Lesson> res = lessonRepository.findById(lessonRecord.getLessonId());
            if (res.isPresent()) {
                lessonRecordDto.setLesson(res.get());
            }
            lessonRecordDto.setId(lessonRecord.getId());
            lessonRecordDto.setBuyTime(lessonRecord.getBuyTime());
            list_result.add(lessonRecordDto);
        }
        return list_result;
    }

    @Override
    public Map<String, Object> getLessonRecordPage(Pageable pageable) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        Page<LessonRecord> page = lessonRecordRepository.findByUserIdWithPage(userId, pageable);
        Page<LessonRecordDto> res = page.map(lessonRecordMapper::toDto);
        List<LessonRecordDto> list = res.getContent();
        for (LessonRecordDto lessonRecordDto : list) {
            lessonRecordDto.setUserDto(userService.findById(lessonRecordDto.getUserId()));
            Optional<Lesson> result = lessonRepository.findById(lessonRecordDto.getLessonId());
            if (result.isPresent()) {
                LessonDto lessonDto = new LessonDto();
                List<LessonRecord> lessonRecordList = lessonRecordRepository.findByLessonId(result.get().getId());
                if (lessonRecordList != null) {
                    lessonDto.setCountBuys(lessonRecordList.size());
                }
                lessonRecordDto.setLesson(result.get());
                lessonRecordDto.setLessonDto(lessonDto);
            }
        }
        return PageUtil.toPage(res);
    }

    @Override
    public Boolean isBuy(Integer lesson_id) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
//        Optional<Lesson> res = lessonRepository.findById(lesson_id);
//        if (!res.isPresent()) {
//            throw new BadRequestException("课程未找到");
//        }
        List<LessonRecord> listLessonRecord = lessonRecordRepository.findByUserIdAndLessonId(userId, lesson_id);
        if (listLessonRecord != null && listLessonRecord.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Map<String, Object> wxShow(LessonWxQueryCriteria criteria, Pageable pageable) {
        Page<Lesson> page = null;
        if (criteria.getIsPush() == null && (criteria.getType() != null && !criteria.getType().equals(""))) {
            page = lessonRepository.findWxListWithType(criteria.getType(), pageable);
        }
        if (criteria.getIsPush() != null && (criteria.getType() != null && !criteria.getType().equals(""))) {
            page = lessonRepository.findWxListWithIsPushWithType(criteria.getIsPush(), criteria.getType(), pageable);
        }
        if (criteria.getIsPush() == null && criteria.getType() == null) {
            page = lessonRepository.findWxList(pageable);
        }
        if (criteria.getIsPush() != null && criteria.getType() == null) {
            page = lessonRepository.findWxListWithIsPush(criteria.getIsPush(), pageable);
        }
        Page<LessonDto> res = page.map(lessonMapper::toDto);
        List<LessonDto> list = res.getContent();
        List<String> listres_label = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            LessonDto lessonDto = list.get(i);

            List<LessonLabel> list_lessonLabels = lessonLabelRepository.findByLessonId(lessonDto.getId());
            if (list_lessonLabels != null && list_lessonLabels.size() > 0) {
                List<String> listlabel = new ArrayList<String>();
                for (LessonLabel lessonLabel : list_lessonLabels) {
                    listlabel.add(lessonLabel.getLabelName());
                }
                lessonDto.setLabels(listlabel);
            }

            List<LessonRecord> lessonRecordList = lessonRecordRepository.findByLessonId(lessonDto.getId());
            if (lessonRecordList != null) {
                lessonDto.setCountBuys(lessonRecordList.size());
            }

            List<LessonFirstChapter> list1 = lessonFirstChapterRepository.findByLessonId(lessonDto.getId());
            List<LessonFirstChapterDto> lessonFirstChapterDtolist = new ArrayList<LessonFirstChapterDto>();
            for (LessonFirstChapter lessonFirstChapter : list1) {
                LessonFirstChapterDto lessonFirstChapterDto = new LessonFirstChapterDto();
                lessonFirstChapterDto.setId(lessonFirstChapter.getId());
                lessonFirstChapterDto.setName(lessonFirstChapter.getName());
                lessonFirstChapterDto.setType(lessonFirstChapter.getType());
                lessonFirstChapterDto.setUrl(lessonFirstChapter.getUrl());
                lessonFirstChapterDto.setLessonSecondChapterList(lessonSecondChapterRepository.findByFirstChapterId(lessonFirstChapter.getId()));
                lessonFirstChapterDtolist.add(lessonFirstChapterDto);
            }
            lessonDto.setLessonFirstChapterList(lessonFirstChapterDtolist);
            try {
                Long userId = SecurityUtils.getCurrentUserId();
                LessonLearnRecord lessonLearnRecord = lessonLearnRecordRepository.findByUserIdAndLessonId(userId, lessonDto.getId());
                if (lessonLearnRecord != null) {
                    lessonDto.setLearn(true);
                } else {
                    lessonDto.setLearn(false);
                }
            } catch (Exception e) {
                lessonDto.setLearn(false);
            }
        }
        return PageUtil.toPage(res);
    }

    @Override
    public Map<String, Object> wxShowByOrgArea(LessonWxQueryCriteria criteria, Pageable pageable) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(xt);
        } catch (Exception e) {

        }

        Page<Lesson> page = null;
        if (criteria.getIsPush() == null && (criteria.getType() != null && !criteria.getType().equals(""))) {
            if (criteria.getOrgArea() == null) {
                page = lessonRepository.findWxListWithTypeByNoOrgArea(criteria.getType(), pageable);
            } else {
                page = lessonRepository.findWxListWithTypeByOrgArea(criteria.getType(), criteria.getOrgArea(), pageable);
            }
        }
        if (criteria.getIsPush() != null && (criteria.getType() != null && !criteria.getType().equals(""))) {
            if (criteria.getOrgArea() == null) {
                page = lessonRepository.findWxListWithIsPushWithTypeByNoOrgArea(criteria.getIsPush(), criteria.getType(), pageable);
            } else {
                page = lessonRepository.findWxListWithIsPushWithTypeByOrgArea(criteria.getIsPush(), criteria.getOrgArea(), criteria.getType(), pageable);
            }
        }
        if (criteria.getIsPush() == null && criteria.getType() == null) {
            if (criteria.getOrgArea() == null) {
                page = lessonRepository.findWxListByNoOrgArea(pageable);
            } else {
                page = lessonRepository.findWxListByOrgArea(criteria.getOrgArea(), pageable);
            }
        }
        if (criteria.getIsPush() != null && criteria.getType() == null) {
            if (criteria.getOrgArea() == null) {
                page = lessonRepository.findWxListWithIsPushByNoOrgArea(criteria.getIsPush(), pageable);
            } else {
                page = lessonRepository.findWxListWithIsPushByOrgArea(criteria.getIsPush(), criteria.getOrgArea(), pageable);
            }
        }
        Page<LessonDto> res = page.map(lessonMapper::toDto);
        List<LessonDto> list = res.getContent();
        List<String> listres_label = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            LessonDto lessonDto = list.get(i);

            List<LessonLabel> list_lessonLabels = lessonLabelRepository.findByLessonId(lessonDto.getId());
            if (list_lessonLabels != null && list_lessonLabels.size() > 0) {
                List<String> listlabel = new ArrayList<String>();
                for (LessonLabel lessonLabel : list_lessonLabels) {
                    listlabel.add(lessonLabel.getLabelName());
                }
                lessonDto.setLabels(listlabel);
            }

            List<LessonRecord> lessonRecordList = lessonRecordRepository.findByLessonId(lessonDto.getId());
            if (lessonRecordList != null) {
                lessonDto.setCountBuys(lessonRecordList.size());
            }

            List<LessonFirstChapter> list1 = lessonFirstChapterRepository.findByLessonId(lessonDto.getId());
            List<LessonFirstChapterDto> lessonFirstChapterDtolist = new ArrayList<LessonFirstChapterDto>();
            for (LessonFirstChapter lessonFirstChapter : list1) {
                LessonFirstChapterDto lessonFirstChapterDto = new LessonFirstChapterDto();
                lessonFirstChapterDto.setId(lessonFirstChapter.getId());
                lessonFirstChapterDto.setName(lessonFirstChapter.getName());
                lessonFirstChapterDto.setType(lessonFirstChapter.getType());
                lessonFirstChapterDto.setUrl(lessonFirstChapter.getUrl());
                lessonFirstChapterDto.setLessonSecondChapterList(lessonSecondChapterRepository.findByFirstChapterId(lessonFirstChapter.getId()));
                lessonFirstChapterDtolist.add(lessonFirstChapterDto);
            }
            lessonDto.setLessonFirstChapterList(lessonFirstChapterDtolist);
            try {
                Long userId = SecurityUtils.getCurrentUserId();
                LessonLearnRecord lessonLearnRecord = lessonLearnRecordRepository.findByUserIdAndLessonId(userId, lessonDto.getId());
                if (lessonLearnRecord != null) {
                    lessonDto.setLearn(true);
                } else {
                    lessonDto.setLearn(false);
                }
            } catch (Exception e) {
                lessonDto.setLearn(false);
            }
        }
        return PageUtil.toPage(res);
    }

    @Override
    public List<DictDetailDto> findAllType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("lesson_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    @Override
    public List<DictDetailDto> findAllTypeByOrgArea(LessonTypeQueryCriteria lessonTypeQueryCriteria) {
        String orgArea = getOrgArea(lessonTypeQueryCriteria);
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("lesson_type");
        dictQueryCriteria.setOrgArea(orgArea);
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public String getOrgArea(LessonTypeQueryCriteria criteria) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return null;
            }
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && res.getOrgArea().equals(all)) {//用的org组织最高看全部
                return null;
            } else {//如果用户的权限不是福建省则 只能看到对应的组织
                return res.getOrgArea();
            }
        }
    }
}
